package com.winning.pmph.ctrl;

import com.alibaba.fastjson.JSON;
import com.winning.pmph.entity.Words;
import com.winning.pmph.service.WordsService;
import com.winning.pmph.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "知识体系管理/词库管理")
@RestController
@RequestMapping("/pmph/action/word")
public class WordsCtrl {
    @Resource
    private WordsService wordsService;

    @ApiOperation(value = "addWord", notes = "新建词语接口")
    @GetMapping("addWord")
    public void addWord(String words) {
        Words word = JSON.parseObject(words, Words.class);
        if (StringUtils.isEmpty(word.getId())) {
            word.setCreatedBy(PMPHAppUtil.getCurrentUserEnName());
            word.setCreatedTime(LocalDateTimeUtil.getNowAsString());
            word.setSourceType(Words.STATUS_NEW);

        }
        word.setStatus(Words.PASS_YES);
        word.setUpdatedBy(PMPHAppUtil.getCurrentUserEnName());
        word.setUpdatedTime(LocalDateTimeUtil.getNowAsString());
        wordsService.saveWords(word);
    }

    @ApiOperation(value = "selectTableData", notes = "获取词语列表接口")
    @GetMapping("selectTableData")
    public Map<String, Object> selectTableData(String name, String tagName, String sourceType, String createdBy,
                                            String updateTime, String currentPage, String pageSize, String radioStatus) {
        Words words = new Words();
        words.setName(name);
        words.setTag(tagName);
        words.setSourceType(sourceType);
        words.setCreatedBy(createdBy);
        words.setCurrentPage(Integer.parseInt(currentPage));
        words.setPageSize(Integer.parseInt(pageSize));
        List<Words> wordsList = wordsService.queryWords(words, radioStatus, updateTime);
        int wordsNum = wordsService.queryWordsNum(words, radioStatus, updateTime);
        Map<String, Object> map = new HashMap<>();
        map.put("tableData", wordsList);
        map.put("totalNum", wordsNum);
        return map;
    }

    /**
     * 下载模板
     *
     * @throws IOException
     */
    @ApiOperation(value = "downLoadWordsTemplate", notes = "下载词语模板")
    @GetMapping("downLoadWordsTemplate")
    public void downLoadWordsTemplate(HttpServletResponse response) throws IOException {
        XSSFWorkbook workbook = getWorkbook();
        response.setContentType("application/xlsx;charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("词语导入模板.xlsx", "UTF-8"));
        workbook.write(response.getOutputStream());
        response.getOutputStream().close();
    }

    @NotNull
    private XSSFWorkbook getWorkbook() {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        // 添加表头内容
        XSSFRow row0 = sheet.createRow(0);
        XSSFCell cell00 = row0.createCell(0);
        cell00.setCellValue("词语名称");
        XSSFCell cell01 = row0.createCell(1);
        cell01.setCellValue("英文名称");
        XSSFCell cell02 = row0.createCell(2);
        cell02.setCellValue("同义词");
        XSSFCell cell03 = row0.createCell(3);
        cell03.setCellValue("词语分类");
        XSSFCell cell04 = row0.createCell(4);
        cell04.setCellValue("词语来源");

        XSSFRow row1 = sheet.createRow(1);
        XSSFCell cell10 = row1.createCell(0);
        cell10.setCellValue("高血压");
        XSSFCell cell11 = row1.createCell(1);
        cell11.setCellValue("hypertension");
        XSSFCell cell12 = row1.createCell(2);
        cell12.setCellValue("blood pressure");
        XSSFCell cell13 = row1.createCell(3);
        cell13.setCellValue("疾病");
        XSSFCell cell14 = row1.createCell(4);
        cell14.setCellValue("");

        XSSFRow row2 = sheet.createRow(2);
        XSSFCell cell20 = row2.createCell(0);
        cell20.setCellValue("糖尿病");
        XSSFCell cell21 = row2.createCell(1);
        cell21.setCellValue("diabetes");
        XSSFCell cell22 = row2.createCell(2);
        cell22.setCellValue("gestational diabetes");
        XSSFCell cell23 = row2.createCell(3);
        cell23.setCellValue("疾病");
        XSSFCell cell24 = row1.createCell(4);
        cell24.setCellValue("知识");

        XSSFRow row3 = sheet.createRow(3);
        XSSFCell cell30 = row3.createCell(0);
        cell30.setCellValue("说明 :以上数据仅是示例，正式导入时，请把除标题外的测试数据删除，本行也请删除");
        return workbook;
    }

    /**
     * 导入词语模板
     *
     * @throws Exception
     */
    @ApiOperation(value = "exportWordsTemplate", notes = "导入词语模板")
    @PostMapping("exportWordsTemplate")
    public void exportWordsTemplate(MultipartFile file) throws Exception {
        XSSFWorkbook workbook = getWordsWorkbook(file);
        XSSFSheet sheet1 = workbook.getSheetAt(0);
        sheet1.getLastRowNum();
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            XSSFSheet sheet = workbook.getSheetAt(i);
            for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                XSSFRow row = sheet.getRow(j);
                if (row == null) {
                    continue;
                }
                XSSFCell name = row.getCell(0);

                Words words = new Words();
                words.setName(ExcelUtil.superOrSubScript2007(name, workbook));
                XSSFCell englishName = row.getCell(1);
                if (englishName == null) {
                    words.setEnglishName("");
                } else {
                    words.setEnglishName(String.valueOf(englishName));
                }
                XSSFCell synonym = row.getCell(2);
                if (synonym == null) {
                    words.setSynonym("");
                } else {
                    words.setSynonym(String.valueOf(synonym));
                }
                XSSFCell tagName = row.getCell(3);
                if (tagName == null) {
                    words.setTag("");
                } else {
                    words.setTag(String.valueOf(tagName));
                }
                XSSFCell sourceType = row.getCell(4);
                if (sourceType == null) {
                    words.setSourceType(Words.STATUS_EXPORT);
                } else {
                    words.setSourceType("导入_" + sourceType);
                }
                words.setStatus(Words.PASS_NO);
                words.setDeleted(Words.DELETED_NO);
                words.setCreatedBy(PMPHAppUtil.getCurrentUserEnName());
                words.setUpdatedBy(PMPHAppUtil.getCurrentUserEnName());
                words.setCreatedTime(LocalDateTimeUtil.getNowAsString());
                words.setUpdatedTime(LocalDateTimeUtil.getNowAsString());
                wordsService.saveOrUpdate(words);
            }
        }
    }

    @NotNull
    private XSSFWorkbook getWordsWorkbook(MultipartFile multipartFile) throws Exception {
        String path = ApplicationContextUtil.BASE_DOWN_FORDER + "words/temp/";
        String fileName = UploadFileUtil.uploadFile(multipartFile, path, false);
        File file = new File(path + fileName);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        if (file.getName().startsWith(".xlsx")) {
            throw new RuntimeException("文件类型错误，文件类型必须为.xlsx");
        }
        FileInputStream inputStream = new FileInputStream(file);
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        return workbook;
    }

    /**
     * 批量审核
     */
    @ApiOperation(value = "bulkAudit", notes = "词语批量审核接口")
    @PostMapping("bulkAudit")
    public void bulkAudit(String ids) {
        String sql = "update words set status = " + Words.PASS_YES + " , updated_time = '" + LocalDateTimeUtil.getNowAsString() + "' where id in " + "('" + ids + "')";
        wordsService.getBaseMapper().executeUpdate(sql);
    }

    /**
     * 一键审核
     */
    @ApiOperation(value = "updateAllWord", notes = "词语一键审核接口")
    @PostMapping("updateAllWord")
    public void updateAllWord(String name,
                              String tagName,
                              String sourceType,
                              String createdBy,
                              String updateTime,
                              String radioStatus) {
        Words words = new Words();
        words.setName(name);
        words.setTag(tagName);
        words.setSourceType(sourceType);
        words.setCreatedBy(createdBy);
        List<Words> words1 = wordsService.getWordsAll(words, radioStatus, updateTime);
        wordsService.allAudit(words1);
    }


    /**
     * 草稿库删除（物理删除）
     */
    @ApiOperation(value = "deleteById", notes = "草稿库删除（物理删除）")
    @GetMapping("deleteById")
    public void deleteById(String id) {
        wordsService.deleteWordById(id);
    }

    /**
     * 正式库删除（逻辑删除）
     */
    @ApiOperation(value = "delete", notes = "正式库删除（逻辑删除）")
    @GetMapping("delete")
    public void delete(String id) {
        wordsService.deleteOfficialWordById(id);
    }

    /**
     * 恢复
     */
    @ApiOperation(value = "restoreWord", notes = "词语恢复接口")
    @GetMapping("restoreWord")
    public void restoreWord(String id) {
         wordsService.restoreWord(id);
    }

    /**
     * 回收站全部删除（物理删除）
     */
    @ApiOperation(value = "allDeleteWord", notes = "词语回收站全部删除（物理删除）")
    @GetMapping("allDeleteWord")
    public void allDeleteWord() {
        wordsService.deleteAllWord();
    }

    /**
     * 回收站全部恢复
     */
    @ApiOperation(value = "allRestoreWord", notes = "词语回收站全部恢复")
    @GetMapping("allRestoreWord")
    public void allRestoreWord() {
        wordsService.restoreAllWord();
    }

    @ApiOperation(value = "KnowledgeAndTerm", notes = "自动导入词语接口")
    @GetMapping("KnowledgeAndTerm")
    public void KnowledgeAndTerm() {
        wordsService.knowledgeAndTerm();
    }
}
